package com.study.talk.app.home.fragment;

import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import com.study.talk.app.base.EventBusBaseFragment;
import com.study.talk.R;
import com.study.talk.adapter.UserListAdapter;
import com.study.talk.app.chat.ChatActivity;
import com.study.talk.app.home.HomeActivity;
import com.study.talk.databinding.FragmentFriendBinding;
import com.study.talk.entity.UserInfo;
import com.study.talk.util.Constants;
import com.study.talk.util.GsonInstance;
import com.study.talk.util.OtherMessage;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

public class FriendFragment extends EventBusBaseFragment {


    HomeActivity activity;
    UserListAdapter userListAdapter;
    private FragmentFriendBinding fragmentFriendBinding;

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        activity = (HomeActivity) getActivity();
    }

    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        fragmentFriendBinding = FragmentFriendBinding.inflate(inflater,container,false);
        initDate();
        return fragmentFriendBinding.getRoot();
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onOtherMessage(OtherMessage message){
        if (message.getEvent() == Constants.UPDATE_FRIEND_LIST) {
            userListAdapter.notifyDataSetChanged();
        }
    }


    private void initDate() {
        userListAdapter = new UserListAdapter(activity.getApp().friendList);
        fragmentFriendBinding.fragmentFriendListView.setAdapter(userListAdapter);
        fragmentFriendBinding.fragmentFriendListView.setEmptyView(fragmentFriendBinding.fragmentFriendEmptyView);
        fragmentFriendBinding.fragmentFriendListView.setOnItemClickListener((adapterView, view1, i, l) -> {
            UserInfo userInfo = activity.getApp().friendList.get(i);
            Intent intent = new Intent(activity.getApplicationContext(), ChatActivity.class);
            intent.putExtra("data", GsonInstance.instance.toJson(userInfo));
            activity.startActivity(intent);
        });
    }
}